//
//  LGTRWZTaskVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/20.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import ZHRefresh

class LGTRWZMainTaskVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource {
    var tableView:UITableView?
    var headView:LGTRWZTaskHeadView?
    var footerView:LGTRWZTaskFooterView?
    var headClickBlock:ClickIndexBlock?
    var adsClickBlock:ClickInfoBlock?
    var page:Int = 1
    var data:Array<TaskModel>?
    var adsArray:Array<Dictionary<String, Any>> = []
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
        self.setInit()
    }
    
    func setBlock(){
        //头部按钮点击
        weak var weakSelf = self
        self.headClickBlock = {(index:Int) in
            let listVC:LGTRWZTaskListVC = LGTRWZTaskListVC()
            listVC.dataType = index
            //listVC.setTitle()
            weakSelf?.navigationController?.pushViewController(listVC, animated: true)
        }
        self.headView?.clickBlock = self.headClickBlock
        self.adsClickBlock = {(index:Int, info:Dictionary<String, Any>) in
            let url:String = info["url"] as? String ?? ""
            LGTViewUtil.share.gotoVC(nav: weakSelf!.navigationController!, currentVC: weakSelf!, urlStr: url, isSystem: false)
        }
        self.headView?.adsClickBlock = self.adsClickBlock
    }
    
    func setInit(){
        self.tableView?.header?.beginRefreshing()
    }
    
    override func setUI() {
        super.setUI()
        self.setBavBarStyle(navBarHiden: true, title: "", back: false)
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: 0.0, width: Double(KScreenW), height: Double(KScreenH) - TabBarH), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.register(LGTRWZTaskViewCell.classForCoder(), forCellReuseIdentifier: "cell")
        self.headView = LGTRWZTaskHeadView.init(reuseIdentifier: "head")
        self.headView?.frame = CGRect.init(x: 0.0, y: 0.0, width: Double(KScreenW), height: NavBarH + SizeFit(341))
        self.tableView?.tableHeaderView = self.headView
        
        self.footerView = LGTRWZTaskFooterView.init(reuseIdentifier: "footer")
        self.footerView?.frame = CGRect.init(x: 0.0, y: 0.0, width: Double(KScreenW), height: SizeFit(219))
        self.tableView?.tableFooterView = self.footerView
        self.tableView?.tableFooterView = nil
        self.tableView?.estimatedRowHeight = 40
        self.tableView?.rowHeight = UITableView.automaticDimension
        
        weak var weakSelf = self
        self.tableView?.header = ZHRefreshHeader.headerWithRefreshing(block: {
            weakSelf?.page = 1
            weakSelf?.tableView?.footer?.endRefreshing()
            weakSelf?.getData()
            weakSelf?.getCount()
            weakSelf?.getBanner()
        })
        
        self.tableView?.footer = ZHRefreshBackNormalFooter.footerWithRefreshing(block: {
            weakSelf?.page += 1
            weakSelf?.tableView?.header?.endRefreshing()
            weakSelf?.getData()
        })
    }
    
    func getCount(){
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: Task_Count_URL, param: [:], success: { (json) in
            
            weakSelf?.headView?.countArray = json["data"] as? Array<Dictionary<String, Any>>
            
        }, failure: { (json) in
            
        })
    }
    
    //banner
    func getBanner(){
        weak var weakSelf = self
        //首页广告
        LGTHttpUtil.httpUtil.requestData(url: Banner_URL, param: ["type": 1], success: { (json) in
            weakSelf?.adsArray = json["data"] as? Array<Dictionary<String, Any>> ?? []
            //刷新数据
            weakSelf?.headView?.imageArray = weakSelf?.adsArray
        }, failure: { (json) in
            
        })
        
        //弹窗
    }
    
    func getData(){
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: Task_List_URL, param: ["page":self.page], showMessage: false, success: { (json) in
            weakSelf?.tableView?.header?.endRefreshing()
            weakSelf?.tableView?.footer?.endRefreshing()
            let data:Array<Dictionary<String, Any>> =  json["data"] as? Array<Dictionary<String, Any>> ?? Array.init()
            var modeArray:Array<TaskModel> = Array.init()
            for i in 0..<data.count{
                let param:Dictionary<String, Any> = data[i]
                let model:TaskModel = try! lgtDecode(TaskModel.self, param: param)
                modeArray.append(model)
            }
            
            if weakSelf?.page == 1{
                 weakSelf?.data = modeArray
                if modeArray.count > 0{
                    weakSelf?.tableView?.tableFooterView = nil
                }else{
                    weakSelf?.tableView?.tableFooterView = weakSelf?.footerView
                }
            }else{
                if weakSelf?.data == nil{
                    weakSelf?.data = Array.init()
                }
                weakSelf?.data?.append(contentsOf: modeArray)
            }
            
            if modeArray.count == 0{
                weakSelf?.tableView?.footer?.endRefreshingWithNoMoreData()
            }else{
                weakSelf?.tableView?.footer?.resetNoMoreData()
            }
            weakSelf?.tableView?.reloadData()
        }, failure: { (json) in
            weakSelf?.tableView?.header?.endRefreshing()
            weakSelf?.tableView?.footer?.endRefreshing()
        })
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        tableView.deselectRow(at: indexPath, animated: false)
        let cell:LGTRWZTaskViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LGTRWZTaskViewCell
        cell.model = self.data?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let taskModel:TaskModel = self.data![indexPath.row]
        let detailVC:LGTPostDetailVC = LGTPostDetailVC()
        detailVC.taskModel = taskModel
        detailVC.viewDetailType = DetailType.RWZ_Task_Detail_Type
        // detailVC.isPreview = false
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //判断是否有弹窗
        if LGTUserUtil.share.getShowRWZHomeAlertState() == true{
            return
        }
        
        //启动弹一次
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: Banner_URL, param: ["type": 2], success: { (json) in
            
            let data:Array<Dictionary<String, Any>> = json["data"] as? Array<Dictionary<String, Any>> ?? []
            if data.count == 0{
                return
            }
            
            let info = data[0]
            let status = info["status"] as? Int ?? 0
            if status != 1{
                return
            }
            
            LGTUserUtil.share.showRWZHomeAlert()
            let vc:HomeAlertVC = HomeAlertVC()
            vc.info = info
            vc.clickInfoBlock = weakSelf?.adsClickBlock
            vc.modalPresentationStyle = .overCurrentContext
            weakSelf?.tabBarController?.present(vc, animated: false, completion: nil)
        }, failure: { (json) in
            
        })
    }
}
